"""
ATZLinux Store Client - 与守护进程通信的客户端库
"""
import json
import socket
import logging
import threading
from queue import Queue

SOCKET_PATH = '/var/run/atzstore-daemon.sock'

class AptClient:
    """与APT守护进程通信的客户端"""
    
    def __init__(self):
        self.socket = None
        self.connected = False
        self.message_queue = Queue()
        self.callbacks = {}
        self.receive_thread = None
        
    def connect(self):
        """连接到守护进程"""
        try:
            self.socket = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
            self.socket.connect(SOCKET_PATH)
            self.connected = True
            
            # 启动接收消息的线程
            self.receive_thread = threading.Thread(target=self._receive_messages)
            self.receive_thread.daemon = True
            self.receive_thread.start()
            
            logging.info("Connected to ATZStore daemon")
            return True
            
        except Exception as e:
            logging.error(f"Failed to connect to daemon: {e}")
            return False
            
    def disconnect(self):
        """断开连接"""
        self.connected = False
        if self.socket:
            self.socket.close()
            self.socket = None
        logging.info("Disconnected from daemon")
        
    def send_message(self, message):
        """发送消息到守护进程"""
        if not self.connected:
            return False
            
        try:
            data = json.dumps(message).encode('utf-8')
            self.socket.send(data)
            return True
        except Exception as e:
            logging.error(f"Failed to send message: {e}")
            return False
            
    def _receive_messages(self):
        """接收消息的线程函数"""
        while self.connected:
            try:
                data = self.socket.recv(4096)
                if not data:
                    break
                    
                message = json.loads(data.decode('utf-8'))
                self.message_queue.put(message)
                
                # 调用相应的回调函数
                msg_type = message.get('type')
                if msg_type in self.callbacks:
                    self.callbacks[msg_type](message)
                    
            except Exception as e:
                if self.connected:
                    logging.error(f"Error receiving message: {e}")
                break
                
        self.connected = False
        
    def ping(self):
        """测试连接"""
        return self.send_message({"type": "ping"})
        
    def execute_apt_command(self, command):
        """执行apt命令"""
        message = {
            "type": "apt_command",
            "command": command
        }
        return self.send_message(message)
        
    def get_installed_packages(self):
        """获取已安装软件包列表"""
        message = {"type": "get_installed_packages"}
        return self.send_message(message)
        
    def set_callback(self, message_type, callback):
        """设置消息回调函数"""
        self.callbacks[message_type] = callback
        
    def get_message(self, timeout=None):
        """获取接收到的消息"""
        try:
            if timeout:
                return self.message_queue.get(timeout=timeout)
            else:
                return self.message_queue.get_nowait()
        except:
            return None